package org.piggy.config.center.nacos;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.piggy.common.rule.Rule;
import org.piggy.config.center.api.ConfigCenter;
import org.piggy.config.center.api.RulesChangeHandler;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Slf4j
public class NacosConfigCenter implements ConfigCenter {
    private static final String config_data_id = "piggy-api-gateway";

    private String serverAddr;

    private String env;

    private ConfigService configService;

    public String getServerAddr() {
        return serverAddr;
    }

    @Override
    public void init(String serverAddr, String env) {
        this.serverAddr = serverAddr;
        this.env = env;
        try {
            configService = NacosFactory.createConfigService(serverAddr);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void subscribeRulesChange(RulesChangeHandler handler) {
        try {
            String config = configService.getConfig(config_data_id, env, 5000);
            log.info("config from nacos: {}", config);
            List<Rule> rules = JSONObject.parseObject(config).getJSONArray("rules").toJavaList(Rule.class);
            handler.onRulesChange(rules);

            configService.addListener(config_data_id, env, new Listener() {
                @Override
                public Executor getExecutor() {
                    return Executors.newSingleThreadExecutor();
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("config from nacos: {}", configInfo);
                    List<Rule> rules = JSON.parseObject(configInfo).getJSONArray("rules").toJavaList(Rule.class);
                    handler.onRulesChange(rules);
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
